package com.itboye.jinpuyiyuan.activity.home.register;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.login.RegistActivity;
import com.itboye.jinpuyiyuan.adapter.BranchListAdapter;
import com.itboye.jinpuyiyuan.adapter.FindDoctorArrayAdapter;
import com.itboye.jinpuyiyuan.adapter.LeftAdapter;
import com.itboye.jinpuyiyuan.adapter.RightAdapter;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.BranchBean;
import com.itboye.jinpuyiyuan.bean.BranchDepartmentBean;
import com.itboye.jinpuyiyuan.bean.BranchDepartmentBeanNew;
import com.itboye.jinpuyiyuan.bean.RegisterDoctorDetail;
import com.itboye.jinpuyiyuan.bean.RegisterHospitalBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.LocationUtils;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Administrator on 2017/12/9 0009.
 * 挂号
 */

public class RegisterActivity extends BaseActivity implements  Observer {
    //title
    private ImageView leftImg,rightImg;
    private TextView leftTv,tvTitle;
    private RelativeLayout rlLeft;


    private BranchAddressPresenter presenter;
    private BroadcastReceiver receiver;
    private HashMap<String,Integer> map=new HashMap<>();//string分院名称，integer 分院id
    private List<BranchDepartmentBeanNew> departmentList;//存放科室
    private List<BranchDepartmentBeanNew.DepartmentChild> childList;//存放科室子科室（如儿科的外科和内科）
    private LinearLayout branchswitch,top_line,sortLl,sortlist_Ll,branchList_Ll;
    private ListView leftList,rightList,switchBranchList,sortList;


    private ArrayList<String> leftarray,rightarray,brancharray;

    private LeftAdapter leftAdapter;
    private RightAdapter rightAdapter;

    private FindDoctorArrayAdapter branchSwitchAdapter//切换分院
            ,sortAdapter;//切换分院

    private TextView branchName,sortTv;
    private PopupWindow switchBranchPop;
    //分院id 科室或诊室deptid
    private String branchId,departmentId;
    private String titleName;
    //分院
    private ArrayList<BranchBean.ListInfo> branchs;
    //departments 科室  consltation 诊室
    private ArrayList<BranchDepartmentBeanNew.DepartmentChild> departments,consultations;
    //type  1 查询科室  2 查询诊室
    private int type=0;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_register_hospital);

        leftTv.setVisibility(View.GONE);
        rightImg.setVisibility(View.GONE);
        tvTitle.setText("挂号");
        branchList_Ll.setVisibility(View.GONE);

//        presenter.queryDepartment(branchs.get(position).getId()+"","0");
        //接受登录和退出登录的广播
        receiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(FilterUtil.LOGIN)){
                  //数据刷新

                }else  if (intent.getAction().equals(FilterUtil.EXITLOGIN)){
                    //登录
                 startActivity(new Intent(RegisterActivity.this, LoginOrRegisterActivity.class));

                }

            }
        };
       registerReceiver(receiver,new IntentFilter(FilterUtil.LOGIN));
       registerReceiver(receiver,new IntentFilter(FilterUtil.EXITLOGIN));
        presenter=new BranchAddressPresenter(this);
        String lngAndLatWithNetwork = new LocationUtils().getLngAndLat(this);
        presenter.queryBranch(lngAndLatWithNetwork.split(",")[0],lngAndLatWithNetwork.split(",")[1]);//分院查询

        leftarray=new ArrayList<>();//科室
        rightarray=new ArrayList<>();//诊室
        brancharray= new ArrayList<>();//分院

        branchs=new ArrayList<>();// 分院
        departments=new ArrayList<>(); //科室
        consultations = new ArrayList<>();//诊室

        switchBranchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                branchName.setText(brancharray.get(position));
                branchList_Ll.setVisibility(View.GONE);
                branchId=branchs.get(position).getId();
                type=1;
                titleName=branchs.get(position).getName();
                presenter.queryDepartment(branchId+"","0");

            }
        });

        leftList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                leftAdapter.cancleAllItemState(position);
                titleName=departments.get(position).getDept_name();
                type=2;
                departmentId=departments.get(position).getDept_id();
                presenter.queryDepartment(branchId+"",departmentId+"");
            }
        });
        rightList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
             titleName=consultations.get(position).getDept_name();
             departmentId=consultations.get(position).getDept_id();
             toActivity();
            }
        });


    }

    @Override
    public void finish() {
        super.finish();
        unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){
            case R.id.rlLeft:
            case R.id.leftImg:
                this.finish();
                break;
            case R.id.branchswitch:
            case R.id.branchswitchImg:
            case R.id.branchswitchTv:
                branchList_Ll.setVisibility(View.VISIBLE);
                break;

            case R.id.branchList_Ll:
                branchList_Ll.setVisibility(View.GONE);
                leftList.setFocusable(true);
                leftList.setFocusableInTouchMode(true);
                break;

        }
    }


    private void toActivity(){

        Intent intent = new Intent(RegisterActivity.this, RegisterDetailActivity.class);
        intent.putExtra("title",titleName);
        intent.putExtra("hid",branchId);
        intent.putExtra("dept_id",departmentId);
        startActivity(intent);
    }
    @Override
    public void update(Observable o, Object arg) {

        ResultEntity entity = handlerError(arg);
        Log.d("======entity",entity.toString());
        if (entity != null) {
            if (entity.getEventType() == BranchAddressPresenter.queryAddress_success) {
//                MAlert.alert("请求成功");
                BranchBean bean = (BranchBean) entity.getData();
                if (brancharray.size()>0){
                    brancharray.clear();
                }
                if (branchs.size()>0){
                    branchs.clear();
                }
//
                Log.d("======up",bean.toString());
                for (int i=0;i<bean.getList().size();i++){
                    branchs.add(bean.getList().get(i));
                    brancharray.add(bean.getList().get(i).getName());
                }
                branchName.setText(brancharray.get(0));
                branchId=branchs.get(0).getId();
                branchSwitchAdapter=new FindDoctorArrayAdapter(this,brancharray);
                switchBranchList.setAdapter(branchSwitchAdapter);
//                //查询科室
                type=1;
                presenter.queryDepartment(bean.getList().get(0).getId()+"","0");
            } else if (entity.getEventType() == BranchAddressPresenter.queryAddress_fail) {
//                MAlert.alert(entity.getMsg(), Gravity.TOP);
            }else if (entity.getEventType()== BranchAddressPresenter.By_HospSect_query_success){
//                MAlert.alert("科室查询成功");
                if (type==1){//科室
                    if (leftarray.size()>0){
                        leftarray.clear();
                    }
                    if (departments.size()>0){
                        departments.clear();
                    }
                    for (int i=0;i< ((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().size();i++){
                        leftarray.add(((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().get(i).getDept_name());
                        departments.add(((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().get(i));
                    }
                    leftAdapter=new LeftAdapter(this,departments);
                    leftList.setAdapter(leftAdapter);

                    if (leftarray.size()>0){
                        departmentId=departments.get(0).getDept_id();
                        type=2;
                        presenter.queryDepartment(branchId+"",departments.get(0).getDept_id());
                    }else {//没有科室
                        //直接跳转排班
                        toActivity();
                        if (rightAdapter!=null){
                            rightAdapter.addData(departments);
                        }
                    }
                }else {
                    if (rightarray.size()>0){
                        rightarray.clear();
                    }
                    if (consultations.size()>0){
                        consultations.clear();
                    }
                    for (int i=0;i< ((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().size();i++){
                        rightarray.add(((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().get(i).getDept_name());
                        consultations.add(((List<BranchDepartmentBeanNew>) entity.getData()).get(0).getSect_list().get(i));
                    }
                    if (rightarray.size()>0){
                        departmentId=consultations.get(0).getDept_id();
                        rightAdapter=new RightAdapter(this,consultations);
                        rightList.setAdapter(rightAdapter);
                    }else {
                     //直接跳转排班
                       toActivity();
                    }
                }

            }else if (entity.getEventType() == BranchAddressPresenter.By_HospSect_query_fail){
//                MAlert.alert("科室查询失败");
            }


        }
    }
}
